﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Jinndev.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.IO;

namespace Jinndev
{

    public class ExportTcbDBUI : BaseUIBehaviour
    {

        #region static
        public static readonly string PATH = "Prefab/UI/ExportTcbDB/ExportTcbDBUI";

        public static ExportTcbDBUI Create()
        {
            return UIManager.Instance.Add<ExportTcbDBUI>(PATH, UIParam.FullScreen);
        }
        #endregion

        public RectTransform exportDirSlot;
        public RectTransform logArea;

        public InputField inputArg1;
        public InputField inputExportFileName;

        public Button btnStart;
        public Image progressBar;
        public Text progressText;

        private InputFileField exportDirField;
        private LogView logView;

        private void Awake()
        {
            logView = LogView.Create(logArea);

            exportDirField = InputFileField.Create(exportDirSlot, new InputFileField.DirectoryOption("导出路径", "选择导出文件的存储路径", OnChooseExportDir));
            if (Directory.Exists(Setting.Instance.exportTcbDir))
                exportDirField.SetPath(Setting.Instance.exportTcbDir, false);

            inputExportFileName.text = "export_";

            progressBar.fillAmount = 0;
            progressText.text = string.Empty;
        }

        private void Update()
        {
            TryInvokeSingleAction();
        }

        private void OnChooseExportDir(string path)
        {
            Setting.Instance.exportTcbDir = path;
            Setting.Save();
        }


        public void OnClickStart()
        {
            progressBar.fillAmount = 0;
            progressText.text = string.Empty;

            if (!long.TryParse(inputArg1.text, out long submitTime))
            {
                logView.LogError($"'{inputArg1.text}' 格式错误");
                return;
            }

            string fileName = inputExportFileName.text;
            if (string.IsNullOrEmpty(fileName))
            {
                logView.LogError($"导出文件名为空");
                return;
            }

            int loop = 10 * 100;
            //long submitTime = 1638246326000;
            //string fileName = "export_00015";

            StartCoroutine(ExportOrderHistory(loop, submitTime, fileName));
        }

        public IEnumerator ExportOrderHistory(int loop, long submitTime, string fileName)
        {
            // db.collection("order-history").where({ submitTime: _.lt(1638246326000) }).count()

            string url = "https://jd-compose-9gjl83dlebd62321-1307535713.ap-shanghai.app.tcloudbase.com/main?method=order%2FgetOrderHistoryList&startTime={0}";
            string outputFile = @$"F:\Work\JingDong\order-history\{fileName}.json";
            if (File.Exists(outputFile))
            {
                logView.LogError($"导出文件已存在");
                yield break;
            }
            btnStart.interactable = false;

            long totalCount = 0;
            for (int i = 0; i < loop; i++)
            {
                yield return new WaitForSecondsRealtime(0.05f);

                var req = UnityWebRequest.Get(string.Format(url, submitTime));
                yield return req.SendWebRequest();

                var text = req.downloadHandler.text;
                var result = JsonConvert.DeserializeObject<ResponseData>(text);

                if (!result.success)
                {
                    logView.LogError(result.message);
                    yield break;
                }
                if (result.data == null || result.data.Length == 0)
                {
                    logView.Log("无数据");
                    yield break;
                }

                foreach (var item in result.data)
                {
                    item.Remove("_id");
                    item.Remove("_updateTime");
                    item.Remove("_createTime");
                    File.AppendAllText(outputFile, JsonConvert.SerializeObject(item, Formatting.None) + "\n");
                }
                totalCount += result.data.Length;
                logView.Log($"({i + 1}/{loop}) 导出: {result.data.Length}, 总计: {totalCount}");
                SetProgressLater(i, loop);
            }
            btnStart.interactable = true;
            logView.Log("导出文件: " + outputFile);
            logView.Log("导出大小: " + CommonUtil.GetFileSizeDesc(outputFile));
            logView.Log("完成");
        }

        private void SetProgressLater(int index, int total)
        {
            EnqueueAction(() => SetProgress(index, total));
        }

        private void SetProgress(int index, int total)
        {
            progressBar.fillAmount = (float)index / total;
            progressText.text = (index) + "/" + total;
        }

    }

}
